<style scoped>
.vendorReturn {
  margin-right: 0.5vw;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}
.vendorReturn_top {
  display: flex;
  padding: 1.5vh 0;
  white-space: nowrap;
}
.t_content {
  margin: 0 5px 0 15px;
  padding-top: 3px;
}
.t_content1 {
  padding-top: 3px;
  margin: 0 6px 0 0;
}

.vendorReturn input:focus {
  outline: none;
  border: 1px solid #017aff;
}
.inp {
  border: 1px solid #dbdbdb;
  border-radius: 3px;
  height: 30px;
  padding: 0 15px;
}
.inp2 {
  width: 7vw;
}
.inp1 {
  width: 7vw;
}
.inp3 {
  width: 4vw;
  margin-right: 10px;
}
.a_color {
  color: #017aff;
}
.vendorStock_c {
  display: flex;
  width: 100%;
  height: 85%;
  border-top: 2px solid #f4f4f4;
}
.content1 {
  width: 35%;
  height: 87vh;
  border-right: 2px solid #f4f4f4;
  padding-right: 10px;
}
.content2 {
  width: 65%;
  height: 87vh;
  padding-left: 10px;
}
.content1_1 {
  display: flex;
  margin: 1.5vh 0;
  overflow: hidden;
}
.hand {
  cursor: pointer;
}
.c2 {
  white-space: nowrap;
  margin: 1.5vh 0;
}
.c2_2 {
  float: right;
}
.c2_1 {
  display: inline-block;
}
.c2_2 p {
  display: inline-block;
  margin-right: 1.5vw;
}
.vendorReturn .check {
  width: 90px;
  height: 40px;
  border: 1px solid #d3cdcd;
  border-radius: 5px;
  padding: 8px 0 0 7px;
}
.c2_button {
  height: 25px;
  margin: 8px 5px 0 35px;
}
.c2_button1 {
  height: 25px;
  margin: 8px 5px 0 0;
}
.content2_1 {
  margin-top: 3px;
}

.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
.footView span i {
  margin-right: 5px;
}
</style>

<style>
.vendorReturn .el-input__icon {
  line-height: 30px;
}
.vendorReturn .el-date-editor {
  width: 7vw;
}
.vendorReturn .vendorReturn_top .el-date-editor .el-input__inner {
  height: 30px;
  padding-right: 0;
  width: 7vw;
}
.vendorReturn .vendorReturn_top .el-select .el-input__inner,
.vendorReturn .content1_1 .el-select .el-input__inner {
  height: 30px;
  width: 5vw;
}
.vendorReturn .vendorReturn_top .ph .el-input__inner {
  height: 30px;
  width: 7vw;
}
.vendorReturn .content1_1 > .el-input {
  width: 10vw;
}
.vendorReturn .content1_1 .el-input__inner {
  height: 30px;
}

.vendorReturn .content1_1 .el-input-group__append,
.el-input-group__prepend {
  padding: 0 15px;
}
.vendorReturn .c2_2 .check {
  width: 70px;
  height: 30px;
  padding: 3px 0 0 7px;
}
.vendorReturn .c2_2 .el-button {
  width: 40px;
}
.vendorReturn .c2_1 .el-button {
  margin: 0 10px 0 0;
}
.vendorReturn .el-input-group__append {
  background-color: #ecf5ff;
  color: #409eff;
}

.vendorReturn .el-table__footer td {
  height: 26px;
}
.vendorReturn .el-table .cell {
  padding: 0 0 0 5px;
}
</style>

<template>
  <div class="vendorReturn">
    <div class="vendorReturn_top">
      <p class="t_content1">退货日期</p>
      <el-date-picker
        v-model="inputDate"
        type="date"
        value-format="yyyy-MM-dd HH:mm:ss"
        placeholder="选择日期"
        disabled
      ></el-date-picker>
      <p class="t_content">厂商编号</p>
      <input
        class="inp inp3"
        type="text"
        v-model="manufacturerNo"
        @blur="manufacturerNoBlur"
      />
      <el-select v-model="manufacturerName" @change="manufacturerNameChange">
        <el-option
          v-for="item in manufacturerList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left">{{ item.value }}</span>
          <span style="float: right">{{ item.label }}</span></el-option
        >
      </el-select>
      <p class="t_content">单号</p>
      <input class="inp inp2" type="text" v-model="odd" />
      <!-- <p class="t_content">厂进序号</p>
      <input class="inp inp2" type="text" v-model="date"> -->
      <p class="t_content">仓库</p>
      <input
        class="inp inp3"
        type="text"
        v-model="companyNo"
        @blur="companyNoBlur"
        disabled
      />
      <el-select
        v-model="companyName"
        @change="
          (e) => {
            this.companyNo = e
          }
        "
        disabled
      >
        <el-option
          v-for="item in warehouseList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left">{{ item.value }}</span>
          <span style="float: right">{{ item.label }}</span></el-option
        >
      </el-select>
      <p class="t_content">品牌</p>
      <div class="ph">
        <el-select v-model="brand">
          <el-option
            v-for="item in brandList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <p class="t_content">配货方式</p>
      <div class="ph">
        <el-select v-model="cooperateWay">
          <el-option
            v-for="item in cooperateWayList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <p class="t_content">备注</p>
      <input class="inp1 inp" type="text" v-model="remark" />
      <p class="t_content a_color hand" @click="modification">修改</p>
      <p class="t_content">折数：{{ discount }}</p>
    </div>

    <div class="vendorStock_c">
      <div class="content1">
        <div class="content1_1">
          <el-select
            v-model="reader"
            style="width: 100px; margin-right: 10px"
            @change="readerChange"
          >
            <el-option
              v-for="item in readerList"
              :key="item.equipmentCabinetNo"
              :label="item.equipmentCabinetNo"
              :value="item.equipmentCabinetNo"
            ></el-option>
          </el-select>
          <el-button icon="el-icon-c-scale-to-original" @click="readRFID"
            >读卡</el-button
          >
          <el-button icon="el-icon-remove-outline" @click="subtract"
            >减标</el-button
          >
          <el-button
            icon="el-icon-delete"
            @click="empty"
            style="margin-right: 10px"
            >清空</el-button
          >
          <el-input v-model="searchRFID" key="vendorStock1">
            <el-button slot="append" style="width: 60px" @click="search"
              >寻标</el-button
            ></el-input
          >
        </div>
        <div class="c_tab">
          <el-table
            ref="table1"
            :data="rfidListTable"
            style="width: 100%"
            height="81vh"
            highlight-current-row
            :header-cell-style="{
              background: '#f4f4f4',
              padding: 0,
              height: '30px'
            }"
            :cell-style="{ padding: 0, height: '26px' }"
            @row-click="rowClick"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column
              prop="index"
              label="序号"
              width="50"
            ></el-table-column>
            <el-table-column prop="showCode" label="RFID"></el-table-column>
            <el-table-column prop="kindsNumber" label="货号"></el-table-column>
            <el-table-column
              prop="sellingPrice"
              label="售价"
              width="100"
            ></el-table-column>
            <el-table-column
              prop="into"
              label="入单"
              width="50"
            ></el-table-column>
          </el-table>
        </div>
      </div>
      <div class="content2">
        <div class="c2">
          <div class="c2_1">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="create"
              :disabled="Boolean(rfidList.length)"
              >新建</el-button
            >
            <el-button
              icon="el-icon-circle-check"
              @click="confirm"
              :disabled="isConfirm"
              >确认</el-button
            >
            <el-button @click="exportExcel">
              <i class="el-icon-upload2"></i>导出</el-button
            >
            <el-button size="small" class="a-upload el-icon-download"
              >导入
              <template>
                <input
                  type="file"
                  accept=".xlsx,.xls"
                  @change="handleImportInputClick"
                  class="file"
                  id="file"
                />
              </template>
            </el-button>
            <!-- <div class="dr">
              <i class="el-icon-download"></i>导入
              <input
                @change="readExcel"
                accept=".xls, .xlsx"
                class="outputlist_upload"
                type="file"
                ref="upload"
              />
            </div> -->
            <el-button @click="printReport">
              <i class="el-icon-printer"></i>列印</el-button
            >
            <el-tooltip
              class="item"
              effect="dark"
              content="说明：品牌库存转为厂退"
              placement="top"
            >
              <el-button icon="el-icon-folder-remove" @click="vrRetreat"
                >存退</el-button
              ></el-tooltip
            >
            <el-button @click="dele" :disabled="isConfirm">
              <i class="el-icon-delete"></i>删除</el-button
            >
          </div>
          <div class="c2_2">
            <p>数量:{{ inputSum }}</p>
            <p>厂退序号:{{ inputSequence }}</p>
            <el-checkbox class="check" v-model="checked">二维</el-checkbox>
            <!-- <el-button icon="el-icon-arrow-left" @click="previousInput"></el-button>
            <el-button icon="el-icon-arrow-right" @click="nextInput"></el-button> -->
          </div>
        </div>
        <div class="content2_1">
          <el-table
            id="outTable"
            :data="switchList"
            style="width: 100%"
            height="81vh"
            highlight-current-row
            ref="table"
            show-summary
            :summary-method="getSummaries"
            :header-cell-style="{
              background: '#f4f4f4',
              padding: 0,
              height: '30px'
            }"
            :cell-style="{ padding: 0, height: '26px' }"
          >
            <el-table-column
              type="index"
              label="序号"
              width="50"
            ></el-table-column>
            <template v-for="i in knhList">
              <el-table-column
                :prop="i.prop"
                :label="i.label"
                :width="i.width"
                :key="i.prop"
                show-overflow-tooltip
              ></el-table-column>
            </template>
          </el-table>
        </div>
      </div>
    </div>
    <new-vr
      :Str="this.Str"
      :style="{ display: showNew_vr }"
      :sendData="sendData"
      :supplementList="supplementList"
      :flag="showNew_vr"
      @closeNewClerk="
        () => {
          this.showNew_vr = 'none'
        }
      "
      @saveNew_vr="saveNew_vr"
      @inpNumChange="
        () => {
          this.inpList = this.getInput()
        }
      "
    ></new-vr>
    <!-- <foot-view class="footView">
    <div slot="text">
    <span>数据库：{{jxQuarter}}</span></div>
    </foot-view> -->
    <print-area
      v-show="false"
      isInput="退"
      isVendor="厂商"
      :manufacturerNo="manufacturerNo"
      :inputSequence="inputSequence"
      :inputDate="inputDate.slice(0, 10)"
      :manufacturerName="printVendorName"
      :principal="contact"
      :phone="phone"
      :address="address"
      :jxQuarter="jxQuarter"
      :printTotal="printTotal"
      :printMoney="printMoney"
      :printStyle="printStyle"
      :printSellingPrice="printSellingPrice"
      :remark="remark"
    ></print-area>
  </div>
</template>

<script>
const resources = require('../../../config/printCSS')

import {
  getManufacturer,
  getBarCode,
  factoryOut,
  affirmRfidOut,
  factoryOutSubtract,
  removeRfidOutPut,
  factoryOutModification,
  outSequenceQuery,
  outQuery,
  retreat,
  renewRepertory,
  searchKindsNumber,
  sequenceRfidList,
  importFactoryOut
} from '../../../network/manufacturer'
import { getWarehouse } from '../../../network/warehouse'
import { getBranded } from '../../../network/branded'
import { getKindsNumberList, postKindsNumber } from '../../../network/artNo'
import {
  connectStatus,
  UHFConnection,
  sendOrder,
  orderList,
  close
} from '../../../network/rfid'
import { getUhfTest } from '../../../network/rfid'
import { internetProtocol } from '../../../config/ip'
import { getQuarter } from '../../../network/quarter'

import newVr from './childComp/newVr'
import footView from '../../../components/FootView'
import printArea from '../../../components/PrintVendorStock'

import today from '../../../components/mixins/today'
import enterUp from '../../../components/mixins/enterUp'
import exportMethods from '../../../components/mixins/exportMethods'
import cookieFn from '../../../components/mixins/cookieFn'

import { importExcel } from '@/util/dealWithExcel'

import XLSX from 'xlsx'
import FileSaver from 'file-saver'

export default {
  name: 'vendor_return_mn',
  mixins: [today, enterUp, exportMethods, cookieFn],
  created() {
    this.inpList = this.getInput()
    this.knhList = this.knhList1

    // 获取厂商信息
    getManufacturer({ limit: 9999 }).then((res) => {
      // console.log(res)
      if (res.data.code == 200) {
        let list = res.data.data
        list.forEach((e) => {
          this.manufacturerList.push({
            value: e.no,
            label: e.name,
            discount: e.discount
          })
        })
        this.newSend()
      }

      // 获取补单 单号
      // console.log(this.$route.query.oid)
      if (this.$route.query.oid) {
        let min =
          new Date().getMinutes() < 10
            ? '0' + new Date().getMinutes()
            : new Date().getMinutes()
        let sec =
          new Date().getSeconds() < 10
            ? '0' + new Date().getSeconds()
            : new Date().getSeconds()
        console.log(this.strRandom + min + sec) //随机字符串加时间      不重复随机字符串
        this.Str = this.strRandom + min + sec
        this.inputSequence = this.$route.query.oid
        this.getData(true)
        if (this.$route.query.type != 1) {
          this.showNew_vr = 'block'
        }
      }
    })
    // 获取季度
    getQuarter().then((res) => {
      if (res.data.code == 200) {
        res.data.data.forEach((e) => {
          this.quarterMap[e.id] = e.name
        })
      }
    })
    // 获取仓库信息
    getWarehouse().then((res) => {
      // console.log(res)
      if (res.data.code == 200) {
        let list = res.data.data
        list.sort((a, b) => {
          return a.no.localeCompare(b.no)
        })
        list.forEach((e) => {
          this.warehouseList.push({
            value: e.no,
            label: e.name,
            company: e.brandedCompany
          })
          if (e.isMainWarehouse) {
            this.companyNo = e.no
            this.companyName = e.name
          }
        })
        this.newSend()
      }
      // console.log(this.warehouseList)
    })

    getUhfTest().then((res) => {
      this.readerList = res.data.data
      this.reader = this.getCookie('RFIDreader') || ''
    })
  },
  data() {
    return {
      Str: '',
      strRandom: Math.random().toString(36).substring(2, 7), //随机字符串
      discount: '',
      quarterMap: {},
      loading: {},
      command: '',
      inpList: [],
      jxQuarter: this.getCookie('jxQuarter'),

      socketId: '',
      ws: {},

      readOnly: false,

      // 厂进序号表
      jList: [],
      // 指针
      pointer: 0,
      // 条码规律详情
      manufacturerBarCode: {},
      // 品牌公司
      brandedCompany: '',

      showNew_vr: 'none',

      inputSum: 0,

      subRFID: [],
      totalDTO: {},
      inputDate: this.searchDateWithHour(),
      manufacturerNo: '',
      manufacturerName: '',
      manufacturerList: [],
      odd: '',
      brand: '',
      brandList: [],
      warehouseList: [],
      companyNo: '',
      companyName: '',
      cooperateWay: '配货',
      cooperateWayList: [
        { value: '配货', label: '配货' },
        { value: '订货', label: '订货' },
        { value: '订断', label: '订断' },
        { value: '追断', label: '追断' }
      ],
      remark: '',

      sendData: {},
      supplementList: [],

      searchRFID: '',
      inputSequence: '',
      checked: false,
      rfidList: [],
      efficacious: [],

      rfidListTable: [],
      allRFIDlist: [],

      switchList: [],
      kindsNumberList: [],
      styleNumberList: [],

      knhList: [],
      knhList1: [
        { prop: 'kindsNumber', label: '货号', width: '160' },
        { prop: 'styleNumber', label: '款号', width: '100', isShow: true },
        { prop: 'colorNo', label: '颜色编号', width: '80', isShow: true },
        { prop: 'colorName', label: '颜色名称', width: '80', isShow: true },
        { prop: 'size', label: '尺码', width: '50', isShow: true },
        { prop: 'sum', label: '数量', width: '80' },
        { prop: 'onePrice', label: '单价', width: '80' },
        { prop: 'money', label: '金额', width: '100' },
        { prop: 'sellingPrice', label: '售价', width: '100' },
        { prop: 'commodityName', label: '品名', width: '160' },
        { prop: 'brandedName', label: '品牌', width: '120' },
        { prop: 'enteringTime', label: '录入时间', width: '160' }
      ],
      knhList2: [
        { prop: 'styleNumber', label: '款号', width: '100' },
        { prop: 'colorNoName', label: '颜色', width: '100' },
        { prop: 'c05', label: '05-XS', width: '100' },
        { prop: 'c07', label: '07-S', width: '100' },
        { prop: 'c09', label: '09-M', width: '100' },
        { prop: 'c11', label: '11-L', width: '100' },
        { prop: 'c13', label: '13-XL', width: '100' },
        { prop: 'c15', label: '15-2L', width: '100' },
        { prop: 'c17', label: '17-3L', width: '100' },
        { prop: 'c19', label: '19-4L', width: '100' },
        { prop: 'c21', label: '21-5L', width: '100' },
        { prop: 'f', label: 'F', width: '80' },
        { prop: 'total', label: '小计', width: '60' },
        { prop: 'sellingPrice', label: '售价', width: '70' },
        { prop: 'sellingPriceMoney', label: '售价金额', width: '100' },
        { prop: 'brandedName', label: '品牌', width: '' },
        { prop: 'quarter', label: '季度', width: '100' }
      ],

      // 当前读卡的原始数据
      originalData: {},

      // 打印
      styleList: [],
      printTotal: 0,
      printMoney: 0,
      // 款号合计
      printStyle: 0,
      printSellingPrice: 0,
      printVendor: '',
      printVendorName: '',
      principal: '',
      contact: '',
      phone: '',
      address: '',
      remark: '',

      isConfirm: false,
      reader: '',
      readerList: [],

      relevanceSizeList: [
        'c05',
        'c07',
        'c09',
        'c11',
        'c13',
        'c15',
        'c17',
        'c19',
        'c21',
        'c23',
        'f'
      ]
    }
  },
  watch: {
    checked(a, b) {
      if (a) {
        this.knhList = this.knhList2
        this.switchList = this.styleNumberList
      } else {
        this.knhList = this.knhList1
        this.switchList = this.kindsNumberList
      }
    },
    pointer(a, b) {
      // console.log(a)
    },
    odd(a, b) {
      this.newNo()
      this.odd = a.toUpperCase().trim()
      this.newSend()
    },
    inputDate(a, b) {
      this.newSend()
    },
    manufacturerNo(a, b) {
      this.newNo()
      this.manufacturerNo = a.toUpperCase().trim()
      this.newSend()
      getManufacturer({ no: a, limit: 99999 }).then((res) => {
        // console.log(res)
        this.printVendorName = res.data.data[0].name
        this.principal = res.data.data[0].principal
        this.contact = res.data.data[0].contact
        this.phone = res.data.data[0].phone
        this.address = res.data.data[0].address
      })
    },
    companyNo(a, b) {
      this.newNo()
      this.companyNo = a.toUpperCase().trim()
      this.newSend()
    },
    cooperateWay(a, b) {
      this.newNo()
      this.newSend()
    },
    remark(a, b) {
      if (a) {
        this.remark = a.toUpperCase().trim()
      }
      this.newNo()
      this.newSend()
    },
    $route(a, b) {
      this.newSend()
      if (b.path.indexOf('delete_document') != -1) {
        this.inputSequence = ''
        this.rfidList = []
        this.efficacious = []

        this.rfidListTable = []
        this.allRFIDlist = []

        this.switchList = []
        this.kindsNumberList = []
        this.styleNumberList = []
        return
      }

      if (a.path.indexOf('/input/vendor_return_mn') != -1 && a.query.oid) {
        this.inpList = this.getInput()
        this.manufacturerList = []
        this.warehouseList = []

        // 获取仓库信息
        getWarehouse().then((res) => {
          // console.log(res)
          if (res.data.code == 200) {
            let list = res.data.data
            list.sort((a, b) => {
              return a.no.localeCompare(b.no)
            })
            list.forEach((e) => {
              this.warehouseList.push({
                value: e.no,
                label: e.name,
                company: e.brandedCompany
              })
              if (e.isMainWarehouse) {
                this.companyNo = e.no
                this.companyName = e.name
              }
            })
            this.newSend()
          }
          // console.log(this.warehouseList)
        })

        // 获取厂商信息
        getManufacturer({ limit: 9999 }).then((res) => {
          // console.log(res)
          if (res.data.code == 200) {
            let list = res.data.data
            list.forEach((e) => {
              this.manufacturerList.push({
                value: e.no,
                label: e.name,
                discount: e.discount
              })
            })
            this.newSend()
          }

          // 获取补单 单号
          // console.log(this.$route.query.oid)
          if (this.$route.query.oid) {
            let min =
              new Date().getMinutes() < 10
                ? '0' + new Date().getMinutes()
                : new Date().getMinutes()
            let sec =
              new Date().getSeconds() < 10
                ? '0' + new Date().getSeconds()
                : new Date().getSeconds()
            console.log(this.strRandom + min + sec) //随机字符串加时间      不重复随机字符串
            this.Str = this.strRandom + min + sec
            this.inputSequence = this.$route.query.oid
            this.getData(true)
            if (this.$route.query.type != 1) {
              this.showNew_vr = 'block'
            }
          }
        })
      }
    },
    searchRFID(a, b) {
      this.searchRFID = a.toUpperCase().trim()
    }
  },
  components: {
    newVr,
    footView,
    printArea
  },
  methods: {
    // 数据变动
    newSend() {
      this.sendData = {
        odd: this.odd,
        inputSequence: this.inputSequence,
        inputDate: this.inputDate,
        manufacturerNo: this.manufacturerNo,
        manufacturerName: this.manufacturerName,
        manufacturerList: this.manufacturerList,
        warehouseList: this.warehouseList,
        companyNo: this.companyNo,
        companyName: this.companyName,
        brand: this.brand,
        brandList: this.brandList,
        cooperateWay: this.cooperateWay
      }
    },
    // 左表点击一行
    rowClick(row, column, event) {
      // console.log(row)
      // console.log(column)
      // console.log(event)
      this.subRFID = [row]
    },
    handleSelectionChange(val) {
      this.subRFID = val
    },

    // 修改
    modification() {
      // if (this.inputSequence) {
      //   this.$alert('请先选择一条退货数据再进行修改操作', '', {
      //     confirmButtonText: '确定'
      //   })
      //   return
      // }
      let d = {
        brandedName: this.brand,
        inputSequence: this.inputSequence,
        inputDate: this.inputDate,
        manufacturerNo: this.manufacturerNo,
        odd: this.odd,
        companyNo: this.companyNo,
        cooperateWay: this.cooperateWay,
        remark: this.remark
      }
      // console.log(d)

      factoryOutModification(JSON.stringify(d)).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        } else {
          this.$message.error('修改失败')
        }
      })
    },

    // 读卡
    // 当厂商上方信息不变，第二次点读卡，要发送厂进序号inputSequence和右表的数据kindsNumberMap, 右表货号数量集kindsNumberNumberMap
    // 第二次读卡返回的rfidlist要增加到左表里
    readRFID() {
      if (!this.inputDate) {
        this.$alert('日期不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.manufacturerNo) {
        this.$alert('厂商不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.companyNo) {
        this.$alert('仓库不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.reader) {
        this.$alert('请选择读卡机', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (this.isConfirm) this.isConfirm = false
      if (this.readOnly) this.readOnly = false

      let host = ''
      let port = ''
      for (const i of this.readerList) {
        if (this.reader == i.equipmentCabinetNo) {
          this.command = i.testHead + i.testBody
          host = i.ip
          port = i.port
          break
        }
      }
      if (!host) {
        this.$alert('请选择读卡机', '', {
          confirmButtonText: '确定'
        })
        return
      }
      this.$message.info('读卡中...等待过长,重读即可！')

      // socketId赋值
      this.socketId = Math.ceil(Math.random() * 1000000) + ''
      this.ws = new WebSocket(
        `wss://${internetProtocol}/webSocket/${this.socketId}`
      )
      this.ws.onopen = (e) => {
        UHFConnection({
          host,
          port,
          socketId: this.socketId
        })
        setTimeout(() => {
          connectStatus({ socketId: this.socketId }).then((res) => {
            if (res.data.code == 200) {
              this.rfidListTable = []
              if (!this.inputSequence) {
                this.rfidList = []
              }
              this.switchList = []
              this.efficacious = []
              this.$message.success('读卡器连接成功,开始读卡')
              sendOrder({
                command: this.command,
                connectId: this.socketId
              })
              this.loading = this.$loading({
                lock: true,
                text: '读卡中...',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, 0)'
              })
            } else if (res.data.code == 201) {
              this.$message.error('读卡器连接失败')
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }, 1500)
      }
      this.ws.onmessage = (e) => {
        // console.log(e)
        if (e.data == '连接成功') return

        let obj = e.data
        obj = JSON.parse(obj)

        if (obj.endCommand) {
          this.$message.success('读卡完成')
          this.loading.close()
          this.ws.close()
          this.rfidAdd()
        }

        if (obj.isConnectError) {
          // 连接异常
          this.$message.error(
            `请检查路由器外网IP是否与此IP一致 ：${obj.connectTimeOutIp}`
          )
          this.loading.close()
          this.ws.close()
        }

        if (obj.validShowCode) {
          if (this.rfidList.length) {
            let exist = 0
            for (const i of this.rfidList) {
              if (i.showCode == obj.validShowCode) {
                exist = 1
                break
              }
            }
            if (!exist) {
              this.rfidList.unshift({ showCode: obj.validShowCode })
              this.efficacious.push({ showCode: obj.validShowCode })
            }
          } else {
            this.rfidList.unshift({ showCode: obj.validShowCode })
            this.efficacious.push({ showCode: obj.validShowCode })
          }
          this.rfidListTable.unshift({
            showCode: obj.validShowCode,
            index: this.rfidListTable.length + 1
          })
        }
        if (obj.otherErrorRFID) {
          if (this.rfidListTable.length) {
            let exist = 0
            for (const i of this.rfidListTable) {
              if (i.showCode.indexOf(obj.otherErrorRFID) != -1) {
                exist = 1
                break
              }
            }
            if (!exist) {
              this.rfidListTable.unshift({
                showCode: obj.otherErrorRFID + '其他错误',
                index: this.rfidListTable.length + 1
              })
            }
          } else {
            this.rfidListTable.unshift({
              showCode: obj.otherErrorRFID + '其他错误',
              index: this.rfidListTable.length + 1
            })
          }
        }
        if (obj.antennaErrorRFID) {
          if (this.rfidListTable.length) {
            let exist = 0
            for (const i of this.rfidListTable) {
              if (i.showCode.indexOf(obj.antennaErrorRFID) != -1) {
                exist = 1
                break
              }
            }
            if (!exist) {
              this.rfidListTable.unshift({
                showCode:
                  obj.antennaErrorRFID + '天线错误' + obj.antennaErrorIndex,
                index: this.rfidListTable.length + 1
              })
            }
          } else {
            this.rfidListTable.unshift({
              showCode:
                obj.antennaErrorRFID + '天线错误' + obj.antennaErrorIndex,
              index: this.rfidListTable.length + 1
            })
          }
        }
      }
      this.ws.onclose = () => {
        // console.log("调转连接已关闭")
      }
      this.ws.onerror = (e) => {
        console.log(e)
      }
    },
    rfidAdd() {
      if (!this.efficacious.length) {
        this.rfidListTable = this.allRFIDlist
        this.switchList = this.kindsNumberList
        return
      }
      // 是否有信息变动
      let isNew = false

      if (JSON.stringify(this.originalData) == '{}') {
        // 第一次点读卡，记录原始数据
        this.originalData.inputDate = this.inputDate
        this.originalData.manufacturerNo = this.manufacturerNo
        this.originalData.odd = this.odd
        this.originalData.companyNo = this.companyNo
        this.originalData.brand = this.brand
        this.originalData.cooperateWay = this.cooperateWay
        this.originalData.remark = this.remark
      } else {
        // 判断是否修改了数据
        for (const key in this.originalData) {
          if (this.originalData.hasOwnProperty(key)) {
            const e = this.originalData[key]
            if (e != this[key]) {
              // 修改了数据 重新赋值
              isNew = true
              this.originalData.inputDate = this.inputDate
              this.originalData.manufacturerNo = this.manufacturerNo
              this.originalData.odd = this.odd
              this.originalData.companyNo = this.companyNo
              this.originalData.brand = this.brand
              this.originalData.cooperateWay = this.cooperateWay
              this.originalData.remark = this.remark
              break
            }
          }
        }
      }

      let kindsNumberNumberMap = {}
      let kindsNumberMap = {}
      if (this.inputSequence != '' && !isNew) {
        // 有进厂序号并且信息没改，再点读卡，传右表
        // console.log('没有数据变动读卡')
        this.kindsNumberList.forEach((e) => {
          kindsNumberNumberMap[e.kindsNumber] = e.sum
          kindsNumberMap[e.kindsNumber] = e
        })
      } else {
        // console.log('第一次或有数据变动读卡')
        // 有数据变动，进厂序号改空
        this.inputSequence = ''
        this.allRFIDlist = []
        this.kindsNumberList = []
      }

      let d = {
        manufacturerDTO: {
          dataSource: 0,
          isNewBox: false,
          isKindsNumber: false,
          brandedName: this.brand,
          inputSequence: this.inputSequence,
          inputDate: this.inputDate,
          manufacturerNo: this.manufacturerNo,
          odd: this.odd,
          companyNo: this.companyNo,
          cooperateWay: this.cooperateWay,
          remark: this.remark,
          kindsNumberNumberMap,
          kindsNumberMap
        },
        rfidList: this.efficacious
      }
      // console.log(d)

      factoryOut(JSON.stringify(d)).then((res) => {
        if (res.data.code == 200) {
          if (res.data.data.totalDTO) {
            this.inputSequence =
              res.data.data.totalDTO.manufacturerDTO.inputSequence
          }

          if (
            res.data.data.noRepertoryList &&
            res.data.data.noRepertoryList.length
          ) {
            // console.log('导出一个txt文本')
            let str = ''
            res.data.data.noRepertoryList.forEach((e) => {
              str += e.showCode + '  ' + e.kindsNumber + '\n'
            })
            this.exportRaw(str, '库存不足.txt')
          }
        }
        if (this.inputSequence) {
          this.getData(false)
        }
      })
    },
    readerChange(e) {
      this.delCookie('RFIDreader')
      this.setCookie('RFIDreader', e, 365)
    },

    // 减标
    // 当左表只剩一条数据时，再减标要请求清空
    subtract() {
      if (!this.subRFID.length) {
        this.$alert('请先点击选择一条数据再进行减标操作', '', {
          confirmButtonText: '确定'
        })
        return
      }

      if (this.subRFID.length == this.rfidListTable.length) {
        this.empty()
        return
      }
      let d = {
        manufacturerDTO: {
          manufacturerNo: this.manufacturerNo,
          inputWarehouseNo: this.companyNo,
          inputSequence: this.inputSequence
        },
        rfidList: this.subRFID
      }

      // console.log(d)
      factoryOutSubtract(JSON.stringify(d)).then((res) => {
        if (res.data.code == 200) {
          this.getData(false)
          this.$message({
            message: '减标成功',
            type: 'success'
          })
          this.subRFID = []
        } else {
          this.$message.error('减标失败')
        }
      })
    },

    // 清空
    empty() {
      if (!this.inputSequence) {
        this.$message.info(`已清空`)
        return
      }
      removeRfidOutPut({
        manufacturerNo: this.manufacturerNo,
        inputWarehouseNo: this.companyNo,
        sequence: this.inputSequence
      }).then((res) => {
        if (res.data.code == 200) {
          this.inputSum = 0
          this.inputSequence = ''

          // 左表清空
          this.allRFIDlist = []
          this.rfidListTable = []
          this.rfidList = []

          // 右表清空
          this.switchList = []
          this.kindsNumberList = []
          this.styleNumberList = []
          this.$message({
            message: '清空成功',
            type: 'success'
          })
        } else {
          this.$message.error('清空失败')
        }
      })
    },

    // 寻标
    search() {
      if (this.searchRFID) {
        let exist = 0
        for (const i of this.allRFIDlist) {
          if (this.searchRFID == i.showCode) {
            this.$refs.table1.setCurrentRow(i)
            this.subRFID = [i]
            exist = 1
            break
          }
        }
        if (!exist) {
          this.$message.error(`RFID${this.searchRFID}不存在`)
        }
      }
    },

    create() {
      this.showNew_vr = 'block'
      if (!this.$route.query.oid) {
        if (this.isConfirm) this.isConfirm = false
        if (this.readOnly) this.readOnly = false
        this.inputSequence = ''
        this.inputSum = 0
        this.rfidListTable = []
        this.allRFIDlist = []
        this.switchList = []
        this.kindsNumberList = []
        this.styleNumberList = []
      }
    },

    // 新建保存之后
    saveNew_vr(i) {
      this.readOnly = true
      this.isConfirm = false

      if (i) {
        this.inputSequence = i
        this.getData(true)
      }
    },

    // 厂商编号，仓库，失去焦点
    manufacturerNoBlur() {
      this.brandList = []

      if (this.manufacturerNo != '') {
        for (const i of this.manufacturerList) {
          if (this.manufacturerNo == i.value) {
            this.manufacturerName = i.label

            // let brandedCompany = ''
            // 厂商编号查找品牌公司
            getManufacturer({ no: this.manufacturerNo, limit: 99999 }).then(
              (res) => {
                for (const i of res.data.data) {
                  if (i.no == this.manufacturerNo) {
                    this.brandedCompany = i.brandedCompany
                    break
                  }
                }

                // 品牌公司查条码规律详情
                getBarCode({ company: this.brandedCompany }).then((res) => {
                  this.manufacturerBarCode = res.data.data[0]
                })

                // 品牌公司查品牌
                getBranded({
                  brandedCompany: this.brandedCompany,
                  limit: 99999
                }).then((res) => {
                  let num = 1
                  res.data.data.forEach((e) => {
                    this.brandList.push({ value: e.name, label: e.name })
                    if (num) {
                      if (!this.brand) this.brand = e.name
                      num = 0
                    }
                  })
                })
              }
            )
            return
          }
        }
        this.$alert('无此厂商编号', '', {
          confirmButtonText: '确定'
        })
        this.manufacturerNo = ''
        this.manufacturerName = ''
      } else {
        this.manufacturerName = ''
      }
    },
    // 选择厂商
    manufacturerNameChange(e) {
      this.manufacturerNo = e
      for (let b of this.manufacturerList) {
        if (e == b.value) {
          this.discount = b.discount
        }
      }
      this.manufacturerNoBlur()
    },
    companyNoBlur() {
      if (this.companyNo != '') {
        for (const i of this.warehouseList) {
          if (this.companyNo == i.value) {
            this.companyName = i.label
            return
          }
        }
        this.$alert('无此仓库编号', '', {
          confirmButtonText: '确定'
        })
        this.companyNo = ''
        this.companyName = ''
      } else {
        this.companyName = ''
      }
    },

    // 确认按钮
    confirm() {
      if (
        this.switchList[0].affirm != undefined &&
        this.switchList[0].affirm == 1
      ) {
        this.$message.warning('此单已确认')
        return
      }
      if (!this.inputSequence) return
      affirmRfidOut({
        inputSequence: this.inputSequence,
        warehouseNo: this.companyNo,
        updateType: 1
      }).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            message: '确认成功',
            type: 'success'
          })
          this.isConfirm = true
        } else {
          this.$message.error('确认失败')
        }
      })
    },
    // 存退
    vrRetreat() {
      // if (!this.inputSequence) return
      if (this.manufacturerNo == '') {
        this.$message.warning('厂商编号不能为空')
        return
      }
      if (this.brand == '') {
        this.$message.warning('品牌不能为空')
        return
      }
      if (this.cooperateWay == '') {
        this.$message.warning('配货方式不能为空')
        return
      }
      let obj = {
        inputDate: this.inputDate,
        manufacturerNo: this.manufacturerNo,
        odd: this.odd,
        companyNo: this.companyNo,
        brandedName: this.brand,
        cooperateWay: this.cooperateWay,
        remark: this.remark
      }
      // console.log(JSON.stringify(obj))
      retreat(JSON.stringify({ manufacturerDTO: obj })).then((res) => {
        console.log(res)
        if (res.data.code == 200) {
          this.$message({
            message: '存退成功',
            type: 'success'
          })
          this.inputSequence =
            res.data.data.totalDTO.manufacturerDTO.inputSequence
          this.switchList = res.data.data.totalDTO.validList
          this.inputSum = this.switchList.reduce((prev, next) => {
            return prev + next.sum
          }, 0)
        } else {
          this.$message.error('存退失败')
        }
      })
    },

    // 列印
    printReport() {
      this.clearPrintTable()
      this.styleList = []
      this.printTotal = 0
      this.printMoney = 0
      this.printStyle = 0
      this.printSellingPrice = 0
      this.$confirm('是否使用A4纸打印', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
        .then(() => {
          // 用A4纸
          // console.log('用A4纸')
          this.openPrint(true)
        })
        .catch((action) => {
          // 用半张A4纸
          if (action == 'cancel') {
            // console.log('用半张A4纸')
            this.openPrint(false)
          }
        })
    },
    openPrint(isA4, x = 1, id = 'printTable') {
      // console.log('openPrint')
      let index = --x
      let printTable = document.getElementById(id)
      let length = this.styleNumberList.length

      for (index; index < length; index++) {
        const e = this.styleNumberList[index]
        // console.log(index)
        // console.log(index+1)
        this.printTotal += Number(e.total)
        this.printMoney += Number(e.money)
        this.printSellingPrice += Number(e.sellingPriceMoney)

        let row = printTable.insertRow(printTable.FetchRowCount)
        row.insertCell(0).innerHTML = index + 1
        row.insertCell(1).innerHTML = e.styleNumber + '-' + e.colorNo
        row.insertCell(2).innerHTML = e.colorName
        row.insertCell(3).innerHTML = e.commodityName
        row.insertCell(4).innerHTML = e.c05
        row.insertCell(5).innerHTML = e.c07
        row.insertCell(6).innerHTML = e.c09
        row.insertCell(7).innerHTML = e.c11
        row.insertCell(8).innerHTML = e.c13
        row.insertCell(9).innerHTML = e.c15
        row.insertCell(10).innerHTML = e.c17
        row.insertCell(11).innerHTML = e.c19
        row.insertCell(12).innerHTML = e.c21
        row.insertCell(13).innerHTML = e.c23
        row.insertCell(14).innerHTML = e.f
        row.insertCell(15).innerHTML = e.total
        row.insertCell(16).innerHTML = e.sellingPrice
        row.insertCell(17).innerHTML = e.sellingPriceMoney

        if (isA4) {
          // console.log(parseInt((index+1)/33))
          // console.log((index+1)%33 == 0)
          if (
            parseInt((index + 1) / 33) &&
            (index + 1) % 33 == 0 &&
            index + 1 != length
          ) {
            // console.log('33倍数')
            let pageIndex = index + 3 - parseInt(index / 33) * 33
            // console.log(pageIndex)
            // console.log(index+1)    // 33
            // console.log(length)     // 36
            let startingPoint = index - 32
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += Number(this.styleNumberList[j].total)
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }

            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'

            let newHead = document.createElement('div')
            newHead.classList.add('addPrintHead')
            newHead.innerHTML = `
              <p class="rightTag" style="top: ${
                ((index + 1) / 33) * 29.7 + 3
              }cm;">白联仓库 红联财务 黄联客户</p>
              <span class="printHead">
                ${this.manufacturerName}${this.jxQuarter}厂商退货单
              </span>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">厂商：${this.manufacturerName}</p>
                <p style="margin: 5px 0;">联系人：${this.contact}</p>
                <p style="margin: 5px 0;">退货序号：${this.inputSequence}</p>
              </div>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">厂商电话：${this.phone}</p>
                <p style="margin: 5px 0;">退货日期：${this.inputDate}</p>
              </div>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">公司地址：${this.address}</p>
              </div>
            `
            newHead.style.pageBreakBefore = 'always'
            this.insertAfter(newHead, printTable)

            let tableId = `printTable${(index + 1) / 33}`
            // console.log(tableId)
            let tableDom = document.createElement('table')
            tableDom.border = '1'
            tableDom.align = 'center'
            tableDom.id = tableId
            tableDom.innerHTML = `
              <thead>
                <tr>
                  <td style="width: 4%;padding: 0;text-align: center;" rowspan="2">序号</td>
                  <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">型色</td>
                  <td style="width: 8%;padding: 0;text-align: center;" rowspan="2">颜色</td>
                  <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">品名</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">05</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">07</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">09</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">11</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">13</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">15</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">17</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">19</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">21</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">23</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;">F</td>
                  <td rowspan="2" style="text-align: center;width: 5%;">数量</td>
                  <td rowspan="2" style="text-align: center;width: 5%;">售价</td>
                  <td rowspan="2" style="text-align: center;">金额</td>
                </tr>
                <tr>
                  <td style="text-align: center;border-top: 1px dotted;border-left: 1px dotted;">XS</td>
                  <td style="text-align: center;border-top: 1px dotted;">S</td>
                  <td style="text-align: center;border-top: 1px dotted;">M</td>
                  <td style="text-align: center;border-top: 1px dotted;">L</td>
                  <td style="text-align: center;border-top: 1px dotted;">XL</td>
                  <td style="text-align: center;border-top: 1px dotted;">2L</td>
                  <td style="text-align: center;border-top: 1px dotted;">3L</td>
                  <td style="text-align: center;border-top: 1px dotted;">4L</td>
                  <td style="text-align: center;border-top: 1px dotted;">5L</td>
                  <td style="text-align: center;border-top: 1px dotted;">6L</td>
                  <td style="text-align: center;border-top: 1px dotted;"></td>
                </tr>
              </thead>
            `
            // console.log(tableDom)
            // console.log(index)
            this.printStyleCount(e.styleNumber)
            this.insertAfter(tableDom, newHead)
            this.openPrint(true, index + 2, tableId)
            return
          }
          if (index + 1 == length) {
            let pageIndex = index + 3 - parseInt(index / 33) * 33
            // console.log('最后一行')
            let startingPoint = index < 33 ? 0 : parseInt(index / 33) * 33
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += Number(this.styleNumberList[j].total)
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }
            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'
          }
        } else {
          if (
            parseInt((index + 1) / 12) &&
            (index + 1) % 12 == 0 &&
            index + 1 != length
          ) {
            // console.log('12倍数')
            let pageIndex = index + 3 - parseInt(index / 12) * 12
            // console.log(pageIndex)
            // console.log(index+1)    // 12
            // console.log(length)     // 36
            let startingPoint = index - 11
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += Number(this.styleNumberList[j].total)
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }

            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'

            let newHead = document.createElement('div')
            newHead.classList.add('addPrintHead')
            newHead.innerHTML = `
              <p class="rightTag" style="top: ${
                ((index + 1) / 12) * 14.85 + 3
              }cm;">白联仓库 红联财务 黄联客户</p>
              <span class="printHead">
                ${this.manufacturerName}${this.jxQuarter}厂商退货单
              </span>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">厂商：${this.manufacturerName}</p>
                <p style="margin: 5px 0;">联系人：${this.contact}</p>
                <p style="margin: 5px 0;">退货序号：${this.inputSequence}</p>
              </div>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">厂商电话：${this.phone}</p>
                <p style="margin: 5px 0;">退货日期：${this.inputDate}</p>
              </div>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">公司地址：${this.address}</p>
              </div>
            `
            newHead.style.pageBreakBefore = 'always'
            this.insertAfter(newHead, printTable)

            let tableId = `printTable${(index + 1) / 12}`
            // console.log(tableId)
            let tableDom = document.createElement('table')
            tableDom.border = '1'
            tableDom.align = 'center'
            tableDom.id = tableId
            tableDom.innerHTML = `
              <thead>
                <tr>
                  <td style="width: 4%;padding: 0;text-align: center;" rowspan="2">序号</td>
                  <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">型色</td>
                  <td style="width: 8%;padding: 0;text-align: center;" rowspan="2">颜色</td>
                  <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">品名</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">05</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">07</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">09</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">11</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">13</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">15</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">17</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">19</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">21</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">23</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;">F</td>
                  <td rowspan="2" style="text-align: center;width: 5%;">数量</td>
                  <td rowspan="2" style="text-align: center;width: 5%;">售价</td>
                  <td rowspan="2" style="text-align: center;">金额</td>
                </tr>
                <tr>
                  <td style="text-align: center;border-top: 1px dotted;border-left: 1px dotted;">XS</td>
                  <td style="text-align: center;border-top: 1px dotted;">S</td>
                  <td style="text-align: center;border-top: 1px dotted;">M</td>
                  <td style="text-align: center;border-top: 1px dotted;">L</td>
                  <td style="text-align: center;border-top: 1px dotted;">XL</td>
                  <td style="text-align: center;border-top: 1px dotted;">2L</td>
                  <td style="text-align: center;border-top: 1px dotted;">3L</td>
                  <td style="text-align: center;border-top: 1px dotted;">4L</td>
                  <td style="text-align: center;border-top: 1px dotted;">5L</td>
                  <td style="text-align: center;border-top: 1px dotted;">6L</td>
                  <td style="text-align: center;border-top: 1px dotted;"></td>
                </tr>
              </thead>
            `
            // console.log(tableDom)
            // console.log(index)
            this.printStyleCount(e.styleNumber)
            this.insertAfter(tableDom, newHead)
            this.openPrint(false, index + 2, tableId)
            return
          }
          if (index + 1 == length) {
            let pageIndex = index + 3 - parseInt(index / 12) * 12
            // console.log('最后一行')
            let startingPoint = index < 12 ? 0 : parseInt(index / 12) * 12
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += Number(this.styleNumberList[j].total)
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }
            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'
          }
        }

        this.printStyleCount(e.styleNumber)
      }

      this.printStyle = this.styleList.length
      // console.log(this.styleList)
      let int = setInterval(() => {
        if (this.printStyle) {
          clearInterval(int)
          let printHtml = document.getElementById('p').innerHTML
          let wind = window.open(
            '',
            'newwindow',
            'height=500, width=1000, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no'
          )
          wind.document.body.innerHTML = printHtml
          let style = document.createElement('style')
          style.type = 'text/css'
          style.innerHTML = resources.printCSS
          wind.document.head.appendChild(style)
          wind.print()
          return false
        }
      }, 500)
    },
    clearPrintTable() {
      let printTable = document.getElementById('printTable')
      let trs = printTable.getElementsByTagName('tr')
      let len = trs.length - 1
      for (let i = len; i > 1; i--) {
        printTable.deleteRow(i)
      }

      let printArea = document.getElementById('p')
      let tables = printArea.getElementsByTagName('table')
      len = tables.length
      for (let i = 1; i < len; i++) {
        tables[1].remove()
      }
      let addPrintHeads = document.getElementsByClassName('addPrintHead')
      len = addPrintHeads.length
      for (let i = 0; i < len; i++) {
        addPrintHeads[0].remove()
      }
    },
    printStyleCount(s) {
      if (!this.styleList.length) {
        this.styleList.push(s)
      } else {
        let exist = 0
        for (const i of this.styleList) {
          // console.log(i)
          if (i == s) {
            exist = 1
            break
          }
        }
        if (!exist) {
          this.styleList.push(s)
        }
      }
    },
    // insertAfter(p,header1) // 因为js没有直接追加到指定元素后面的方法 所以要自己创建一个方法
    insertAfter(newElement, targetElement) {
      // newElement是要追加的元素 targetElement 是指定元素的位置
      let parent = targetElement.parentNode // 找到指定元素的父节点
      if (parent.lastChild == targetElement) {
        // 判断指定元素的是否是节点中的最后一个位置 如果是的话就直接使用appendChild方法
        parent.appendChild(newElement, targetElement)
      } else {
        parent.insertBefore(newElement, targetElement.nextSibling)
      }
    },

    dele() {
      if (!this.inputSequence) return
      this.$router.push({
        path: '/delete_document',
        query: { type: 2, sequence: this.inputSequence }
      })
      this.$store.commit('addNav', {
        label: '厂商退货删单',
        name: 'delete_document'
      })
    },

    // 导出
    exportExcel() {
      let xlsxParam = { raw: true } //转换成excel时，使用原始的格式
      let wb = XLSX.utils.table_to_book(
        document.querySelector('#outTable'),
        xlsxParam
      )
      let wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream;charset=utf-8' }),
          '厂商退货.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    //表格导入  只有厂进有可能有没建档的货号
    async handleImportInputClick(evt) {
      const params = {
        no: '厂商编号',
        warehouseNo: '仓库编号',
        kindsNumber: '货号',
        number: '数量'
      }
      const dataList = await importExcel(evt, params)
      const { data } = await importFactoryOut(dataList)
      if (data && data.code === 200) {
        this.$message.success(data.msg)
        this.switchList = data.data || []
      }
    },
    // readExcel(e) {
    //   if (!this.inputDate) {
    //     this.$alert('日期不能为空', '', {
    //       confirmButtonText: '确定'
    //     })
    //     this.$refs.upload.value = ''
    //     return
    //   }
    //   if (!this.manufacturerNo) {
    //     this.$alert('厂商不能为空', '', {
    //       confirmButtonText: '确定'
    //     })
    //     this.$refs.upload.value = ''
    //     return
    //   }
    //   if (!this.companyNo) {
    //     this.$alert('公司仓库不能为空', '', {
    //       confirmButtonText: '确定'
    //     })
    //     this.$refs.upload.value = ''
    //     return
    //   }

    //   if (this.readOnly) this.readOnly = false

    //   this.tmpKindsNumberList = []
    //   let that = this
    //   let lastKN = []

    //   if (this.kindsNumberList.length) {
    //     this.kindsNumberList.forEach((e) => {
    //       lastKN.push(e.kindsNumber)
    //     })
    //   }

    //   const files = e.target.files
    //   // console.log(files)
    //   if (files.length <= 0) {
    //     //如果没有文件名
    //     return false
    //   } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
    //     this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
    //     return false
    //   }

    //   const fileReader = new FileReader()
    //   fileReader.onload = (ev) => {
    //     try {
    //       const data = ev.target.result
    //       const workbook = XLSX.read(data, {
    //         type: 'binary'
    //       })
    //       const wsname = workbook.SheetNames[0] //取第一张表
    //       const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
    //       console.log(ws)

    //       // 是否有信息变动
    //       let isNew = false

    //       if (JSON.stringify(that.originalData) == '{}') {
    //         // 第一次点，记录原始数据
    //         that.originalData.inputDate = that.inputDate
    //         that.originalData.manufacturerNo = that.manufacturerNo
    //         that.originalData.odd = that.odd
    //         that.originalData.companyNo = that.companyNo
    //         that.originalData.cooperateWay = that.cooperateWay
    //         that.originalData.remark = that.remark
    //       } else {
    //         // 判断是否修改了数据
    //         for (const key in that.originalData) {
    //           if (that.originalData.hasOwnProperty(key)) {
    //             const e = that.originalData[key]
    //             if (e != that[key]) {
    //               // 修改了数据 重新赋值
    //               isNew = true
    //               that.originalData.inputDate = that.inputDate
    //               that.originalData.manufacturerNo = that.manufacturerNo
    //               that.originalData.odd = that.odd
    //               that.originalData.companyNo = that.companyNo
    //               that.originalData.cooperateWay = that.cooperateWay
    //               that.originalData.remark = that.remark
    //               break
    //             }
    //           }
    //         }
    //       }

    //       if (that.inputSequence != '' && !isNew) {
    //         // 有序号并且信息没改，再点，和补单一样操作
    //         // 补单新增的货号放在kindsNumberNumberMap
    //         // 原有货号不管有没有修改数量，都将原来数据放在kindsNumberMap
    //         // console.log('没有数据变动')
    //       } else {
    //         // console.log('第一次或有数据变动')
    //         // 有数据变动，进厂序号改空
    //         that.inputSequence = ''
    //         this.switchList = []
    //         this.kindsNumberList = []
    //         this.styleNumberList = []
    //       }

    //       let kindsNumberNumberMap = {}
    //       let kindsNumberMap = {}

    //       that.kindsNumberList.forEach((e) => {
    //         kindsNumberMap[e.kindsNumber] = e
    //       })
    //       ws.forEach((e) => {
    //         let kn = e.货号.toString().toUpperCase().trim()
    //         kindsNumberNumberMap[kn] = e.数量
    //       })

    //       let checkParams = {
    //         manufacturerNo: this.manufacturerNo,
    //         companyNo: this.companyNo,
    //         kindsNumberNumberMap
    //       }
    //       let tmpList = ''
    //       // console.log(checkParams)
    //       renewRepertory(JSON.stringify(checkParams))
    //         .then((res) => {
    //           if (res.data.data) {
    //             tmpList = String(res.data.data)
    //             that.exportRaw(tmpList, '库存不足.txt')
    //             kindsNumberNumberMap = {}
    //             ws.forEach((e) => {
    //               let kn = e.货号.toString().toUpperCase().trim()
    //               if (!tmpList.includes(kn)) {
    //                 kindsNumberNumberMap[kn] = e.数量
    //               }
    //             })
    //           }
    //           let d = {
    //             manufacturerDTO: {
    //               discount: this.discount,
    //               dataSource: 1,
    //               isNewBox: true,
    //               isKindsNumber: true,
    //               brandedName: '',
    //               inputSequence: that.inputSequence,
    //               inputDate: that.inputDate,
    //               manufacturerNo: that.manufacturerNo,
    //               odd: that.odd,
    //               companyNo: that.companyNo,
    //               cooperateWay: that.cooperateWay,
    //               inputWarehouseNo: this.companyNo,
    //               companyNo: this.companyNo,
    //               remark: that.remark,
    //               kindsNumberNumberMap,
    //               kindsNumberMap
    //             },
    //             rfidList: []
    //           }
    //           return factoryOut(JSON.stringify(d))
    //         })
    //         .then((r) => {
    //           if (r.data.code == 200) {
    //             this.$message({
    //               message: '导入成功',
    //               type: 'success'
    //             })
    //             that.inputSequence =
    //               r.data.data.totalDTO.manufacturerDTO.inputSequence
    //             that.getData(false)
    //           } else {
    //             this.$message.error('导入失败')
    //           }
    //         })
    //       this.$refs.upload.value = ''
    //     } catch (e) {
    //       return false
    //     }
    //   }
    //   fileReader.readAsBinaryString(files[0])
    // },

    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const prop = column.property
        const values = data.map((item) => Number(item[prop]))
        if (!values.every((value) => isNaN(value))) {
          if (
            prop == 'c05' ||
            prop == 'c07' ||
            prop == 'c09' ||
            prop == 'c11' ||
            prop == 'c13' ||
            prop == 'c15' ||
            prop == 'c17' ||
            prop == 'c19' ||
            prop == 'c21' ||
            prop == 'c23' ||
            prop == 'f' ||
            prop == 'total' ||
            prop == 'sum' ||
            prop == 'money'
          ) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            if (!sums[index]) {
              sums[index] = ''
            }
            let decimal = sums[index].toString().split('.')[1]
            if (decimal && decimal.length > 2) {
              sums[index] = sums[index].toFixed(2)
            }
          }
        }
      })
      return sums
    },

    newNo() {
      if (this.$route.query.oid || this.readOnly) return
      this.inputSequence = ''
      this.rfidList = []
      this.efficacious = []

      this.rfidListTable = []
      this.allRFIDlist = []

      this.switchList = []
      this.kindsNumberList = []
      this.styleNumberList = []

      this.inputSum = 0
      this.originalData = {}
      this.isConfirm = false
    },

    getData(fill) {
      outQuery(
        JSON.stringify({
          sequence: this.inputSequence,
          pageData: {
            page: 1,
            limit: 999
          }
        })
      ).then((res) => {
        if (!res.data.data) {
          return
        }
        if (fill) {
          let obj = res.data.data.resultList[0]
          this.manufacturerNo = obj.manufacturerNo
          this.inputDate = obj.purchaseTime.slice(0, 10) + ' 12:00:00'
          this.odd = obj.receiptsNumber
          this.companyNo = obj.warehouseNo
          this.brand = obj.brandedName
          this.cooperateWay = obj.cooperateWay
          this.remark = obj.remark

          this.manufacturerNoBlur()
          this.companyNoBlur()
        }

        this.kindsNumberList = res.data.data.resultList[0].detailVOList
        this.supplementList = this.kindsNumberList
        this.styleNumberList = res.data.data.allTwoList
        this.inputSum = res.data.data.totalNumber

        this.kindsNumberList.forEach((e) => {
          e.knInfo = e.kindsNumber
          e.kindsNumber = e.knInfo.kindsNumber
          e.styleNumber = e.knInfo.styleNumber
          e.colorName = e.knInfo.colorName
          e.colorNo = e.knInfo.colorNo
          e.size = e.knInfo.size
          e.sizeNo = e.knInfo.sizeNo
          e.commodityName = e.knInfo.commodityName
          e.brandedName = e.knInfo.brandedName
        })

        this.styleNumberList.forEach((e) => {
          e.styleNumber = e.typeNumber
          e.total = e.subTotal
          e.colorNoName = e.colorNo + '.' + e.colorName
          e.quarterName = this.quarterMap[e.quarter]
          e.sellingPriceMoney = (e.sellingPrice * e.subTotal).toFixed(2)
        })

        if (this.checked) {
          this.switchList = this.styleNumberList
        } else {
          this.switchList = this.kindsNumberList
        }

        this.$nextTick(() => {
          this.$refs.table.doLayout()
        })
      })
      sequenceRfidList({
        sequence: this.inputSequence,
        type: 2
      }).then((res) => {
        this.allRFIDlist = res.data.data || []
        let len = this.allRFIDlist.length
        this.rfidListTable = this.allRFIDlist
        this.rfidList = []
        this.allRFIDlist.forEach((e) => {
          e.index = len--
          this.rfidList.push({ showCode: e.showCode })
        })
      })
    }
  },
  beforeDestroy() {
    if (this.ws.readyState == 1) this.ws.close()
  }
}
</script>
